
package ajjj.kiviq.facades;

import ajjj.kiviq.remoteInterfaces.IRemoteUser;
import ajjj.kiviq.entities.UserEnt;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author jeklund
 */
@Stateless
public class UserFacade implements IRemoteUser {

    @PersistenceContext(unitName = "kiviq_pu")
    private EntityManager em;
    
    /**
     * Finds a UserEnt object with the given name
     * @param userName
     * @return the UserEnt object found, null otherwise
     */
    @Override
    public UserEnt findUser(String userName) {
        try {
            TypedQuery<UserEnt> q = em.createNamedQuery("findAllUsersWithName", UserEnt.class);
            q.setParameter("name", userName);
        return q.getSingleResult();
        } catch (Exception e) { //No user found
            return null;
        }        
    }
    
    /**
     * Saves a UserEnt object to the database
     * @param ue 
     */
    @Override
    public void addUser(UserEnt ue) {
        em.persist(ue);
    }
    
    /**
     * Updates a UserEnt object
     * @param ue 
     */
    @Override
    public void updateUser(UserEnt ue) {
        em.merge(ue);
    }
    
    /**
     * Removes a UserEnt from the database
     * @param ue 
     */
    @Override
    public void removeUser(UserEnt ue) {
        em.remove(em.merge(ue));
    }
    
}
